package com.flex.core.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.flex.constants.SystemConstants;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 
 * 在sturts.xml中配置的过滤器，如果没登陆则跳转到指定地址
 * 
 * @author radio 
 * 
 */
public class LoginInterceptor implements Interceptor {

	/**
	 * 需要在sturts.xml中配置拦截器时进行配置的要跳转到的路径地址
	 */
	private String path;

	private static final long serialVersionUID = -4911122707518868115L;

	public void destroy() {
	}

	public void init() {
	}

	/**
	 * 拦截action，从session中取出userID，如果不存在则立刻跳转到指定的地址
	 */
	public String intercept(ActionInvocation ai) throws Exception {
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		Object obj = (Object) session
				.getAttribute(SystemConstants.USER_SESSION_KEY);
		if (obj == null) {
			StringBuffer sb = new StringBuffer();
			sb.append("0; URL=");
			sb.append(req.getContextPath());
			sb.append(path);
			ServletActionContext.getResponse().setHeader("Refresh",
					sb.toString());
			return null;
		} else {
			return ai.invoke();
		}
	}

	public void setPath(String path) {
		this.path = path;
	}
}